﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace TextTools
{
    /// <summary>
    /// FileComp.xaml 的交互逻辑
    /// </summary>
    public partial class FileComp : Window
    {
        public class CompInfo
        {
            public int fcFlag { get; set; }
            public string fcpath1 { get; set; }
            public string fcpath2 { get; set; }
        }

        public FileComp()
        {
            InitializeComponent();
        }
        private string sfilepath = "";
        private string dfilepath = "";
        List<CompInfo> mycis = new List<CompInfo>();

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            sfilepath = sDirText.Text;
            System.Windows.Forms.FolderBrowserDialog tfbd = new System.Windows.Forms.FolderBrowserDialog();
            if (!string.IsNullOrWhiteSpace(sfilepath)) tfbd.SelectedPath = sfilepath;
            if (tfbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                sfilepath = tfbd.SelectedPath;
                sDirText.Text = sfilepath;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            dfilepath = dDirText.Text;
            System.Windows.Forms.FolderBrowserDialog tfbd = new System.Windows.Forms.FolderBrowserDialog();
            if (!string.IsNullOrWhiteSpace(dfilepath)) tfbd.SelectedPath = dfilepath;
            if (tfbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dfilepath = tfbd.SelectedPath;
                dDirText.Text = dfilepath;
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {// 交换目录
            sfilepath = sDirText.Text;
            dfilepath = dDirText.Text;
            string tstr = sfilepath;
            sfilepath = dfilepath;
            dfilepath = tstr;
            sDirText.Text = sfilepath;
            dDirText.Text = dfilepath;
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        { // 分析比较目录
            sfilepath = sDirText.Text;
            dfilepath = dDirText.Text;
            if (string.IsNullOrWhiteSpace(sfilepath))
            {
                ShowInfo.Content = "【目录1】没有选定目录，无法操作！";
                return;
            }
            if (string.IsNullOrWhiteSpace(dfilepath))
            {
                ShowInfo.Content = "【目录2】没有选定目录，无法操作！";
                return;
            }

            ShowInfo.Content = "开始分析比较目录...";
            mycis.Clear();
            ThinkDirFun(sfilepath, dfilepath, "", 0);

            CompListView.Items.Clear();
            foreach (CompInfo tci in mycis)
            {
                CompListView.Items.Add(tci);
            }
            ShowInfo.Content = "分析比较目录完成...";
        }
        /// <summary>
        /// 分析添加目录差异文件到列表，递归所有子文件夹
        /// </summary>
        /// <param name="tPath1">源目录路径</param>
        /// <param name="tPath2">目标目录路径</param>
        /// <param name="tPath3">相对子文件夹</param>
        /// <param name="level">子文件夹层级</param>
        private void ThinkDirFun(string tPath1, string tPath2, string tPath3 = "", int level = 0)
        {
            string sPath = tPath1;
            string dPath = tPath2;
            string tPath = tPath3;
            bool isAdd = false;
            string filterStr = "System Volume Information|$RECYCLE.BIN";
            if (tPath3 != "" && filterStr.IndexOf(tPath) != -1) return;
            try
            {
                System.IO.DirectoryInfo tdi = new System.IO.DirectoryInfo(unionDir(sPath, tPath));
                System.IO.FileInfo[] tfis = tdi.GetFiles();
                System.IO.DirectoryInfo[] tdis = tdi.GetDirectories();
                foreach (System.IO.DirectoryInfo ttdi in tdis)
                {
                    ThinkDirFun(sPath, dPath, unionDir(tPath, ttdi.Name), level + 1);
                }
                foreach (System.IO.FileInfo ttfi in tfis)
                {
                    tPath = ttfi.FullName.Substring(sPath.Length);
                    CompInfo tci = new CompInfo();
                    tci.fcFlag = 0;
                    tci.fcpath1 = unionDir(tPath3, ttfi.Name);
                    if (System.IO.File.Exists(unionDir(dPath, tPath)) == false)
                    {
                        tci.fcFlag = 1;
                        tci.fcpath2 = "不存在";
                    }
                    else
                    {
                        System.IO.FileInfo ttfi2 = new System.IO.FileInfo(unionDir(dPath, tPath));
                        if (ttfi.Length != ttfi2.Length)
                        {
                            tci.fcFlag = 1;
                            tci.fcpath2 = "不一样";
                        }
                    }
                    mycis.Add(tci);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        /// <summary>
        /// 连接两个文件名部分
        /// </summary>
        /// <param name="str1">目录部分</param>
        /// <param name="str2">相对目录的另外部分</param>
        /// <returns>合成完成文件名</returns>
        private string unionDir(string str1, string str2)
        {
            if (string.IsNullOrWhiteSpace(str1)) str1 = str2;
            else if (string.IsNullOrWhiteSpace(str2)) return str1;
            else
            {
                if (str1.Substring(str1.Length - 1) == "\\")
                {
                    if (str2[0] == '\\') str1 = str1 + str2.Substring(1);
                    else str1 = str1 + str2;
                }
                else
                {
                    if (str2[0] == '\\') str1 = str1 + str2;
                    else str1 = str1 + "\\" + str2;
                }
            }
            return str1;
        }

        private void listView1_ClickHead(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is GridViewColumnHeader)
            {
                GridViewColumn clickColumn = (e.OriginalSource as GridViewColumnHeader).Column; //得到单击的列
                if (clickColumn != null)
                {
                    string allstrs="标记|目录|说明";
                    if (allstrs.IndexOf(clickColumn.Header.ToString())>-1)
                    {
                        string bingingProperty = (clickColumn.DisplayMemberBinding as Binding).Path.Path; //得到单击列所绑定的属性
                        System.ComponentModel.SortDescriptionCollection sdc = CompListView.Items.SortDescriptions;
                        System.ComponentModel.ListSortDirection sortDirection = System.ComponentModel.ListSortDirection.Ascending;
                        if (sdc.Count > 0)
                        {
                            System.ComponentModel.SortDescription sd = sdc[0];
                            sortDirection = (System.ComponentModel.ListSortDirection)((((int)sd.Direction) + 1) % 2);
                            ////判断此列当前的排序方式:升序0,倒序1,并取反进行排序。
                            sdc.Clear();

                        }
                        sdc.Add(new System.ComponentModel.SortDescription(bingingProperty, sortDirection));
                    }
                }
            }
        }
        private void OnListItemDoubleClick(object sender, MouseButtonEventArgs e)
        {
            sfilepath = sDirText.Text;
            dfilepath = dDirText.Text;
            if (string.IsNullOrWhiteSpace(sfilepath))
            {
                ShowInfo.Content = "【目录1】没有选定目录，无法操作！";
                return;
            }
            if (string.IsNullOrWhiteSpace(dfilepath))
            {
                ShowInfo.Content = "【目录2】没有选定目录，无法操作！";
                return;
            }
            int selnum = CompListView.SelectedIndex;
            if (selnum == -1)
            {
                ShowInfo.Content = "没有选定对象，无法操作！";
                return;
            }
            CompInfo tci = CompListView.Items[selnum] as CompInfo;
            if (tci.fcFlag == 0)
            {
                ShowInfo.Content = "两个完成一样的文件，无需比较！";
                return;
            }
            if (tci.fcpath2 == "不存在")
            {
                ShowInfo.Content = "不存在的文件，无需比较！";
                return;
            }
            ContentComp tcc=new ContentComp(unionDir(sfilepath,tci.fcpath1),unionDir(dfilepath,tci.fcpath1));
            tcc.Owner=this;
            tcc.Show();
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            if (CompListView.Items.Count < 1)
            {
                ShowInfo.Content = "没有可分析的对象。";
                return;
            }
            sfilepath = sDirText.Text;
            dfilepath = dDirText.Text;
            if (string.IsNullOrWhiteSpace(sfilepath))
            {
                ShowInfo.Content = "【目录1】没有选定目录，无法操作！";
                return;
            }
            if (string.IsNullOrWhiteSpace(dfilepath))
            {
                ShowInfo.Content = "【目录2】没有选定目录，无法操作！";
                return;
            }
            ShowInfo.Content = "开始二次分析....";
            List<CompInfo> doubleThinks = new List<CompInfo>();
            bool issame = true;
            foreach (CompInfo tci in CompListView.Items)
            {
                if (tci.fcFlag == 0 || tci.fcpath2 != "不一样")
                {
                    doubleThinks.Add(tci);
                    continue;
                }
                List<string> fcontent1 = getfilecontent(unionDir(sfilepath,tci.fcpath1));
                List<string> fcontent2 = getfilecontent(unionDir(dfilepath,tci.fcpath1));
                int filenum1 = fcontent1.Count();
                int filenum2 = fcontent2.Count();
                issame = true;
                if (filenum1 != filenum2) issame = false;
                if (issame)
                {
                    for (int i = 0; i < filenum1; i++)
                    {
                        if (fcontent1[i] != fcontent2[i])
                        {
                            issame = false;
                            break;
                        }
                    }
                }
                if (issame) { tci.fcFlag = 0; tci.fcpath2 = ""; }
                doubleThinks.Add(tci);
                Dispatcher.Invoke(new Action(() =>
                {
                    ShowInfo.Content = tci.fcpath1 + " finish...";
                }), System.Windows.Threading.DispatcherPriority.Render);
                fcontent1.Clear();
                fcontent2.Clear();
            }
            CompListView.Items.Clear();
            foreach (CompInfo tci2 in doubleThinks)
            {
                CompListView.Items.Add(tci2);
            }

            ShowInfo.Content = "二次分析完成！";
        }
        private List<string> getfilecontent(string tfn)
        {
            string[] strs = EncodingType.GetFileString(tfn).Split('\n');
            List<string> outstrs = new List<string>();
            string str;
            foreach (string tstr in strs)
            {
                str = tstr.Trim();
                str = str.Replace("\r", "");
                if (string.IsNullOrWhiteSpace(str)) continue;
                outstrs.Add(str);
            }
            return outstrs;
        }
    }
}
